package com.ry;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ry.util.timepick.R;

public class LoginAndRegisterActivity extends Activity {
	
	private static final String TAG = "LoginAndRegisterActivity";
	
	private Button btnBack;
	private TextView tvTittle;
	private Button btnLeft;
	private Button btnRight;
	private LinearLayout llytLogin;
	private LinearLayout llytRegister;
	
	//Login
	private EditText etLogin_phonenum;
	private EditText etLogin_pwd;
	private TextView tvForget_pwd;
	private Button btnLogin;
	//Register
	private EditText etPhonenum;
	private EditText etPwd;
	private EditText etConfirm_pwd;
	private EditText etName;
	private TextView tvRead_treaty;
	private Button btnRegister;
	
	//get value
	private String login_phonenum;
	private String login_pwd;
	private String phonenum;
	private String pwd;
	private String confirm_pwd;
	private String bitchName;
	
	private String tmDevice;
	private String tmSerial;
	private String androidId;
	private String uniqueId;
	private TelephonyManager tm ;
	
	//private static final String HOST_URL = "http://www.rongyitech.com:6060";
	private static final String HOST_URL = "www.rongyitech.com:6060";  

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_and_register);
		init();
		gitUuid();
		getConnection();
		
	}
	
	private void getConnection(){
		//String url = HOST_URL + "/user_sessions";
		String url = "http://www.rongyitech.com:6060/user_sessions";
		HttpClient client = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);
		try {
//			utf8:✓
//			authenticity_token:+RELytAu1P19+G2SFAfHJ6WUqAov/h/SFGkHWJf65uM=
//			[username]:kwashing
//			[password]:123456
//			commit:登录
			
//			List<NameValuePair> nvps = new ArrayList<NameValuePair>();  
//			nvps.add(new BasicNameValuePair("[username]", "kwashing"));  
//			nvps.add(new BasicNameValuePair("[password]", "123456"));  
//			nvps.add(new BasicNameValuePair("commit", "登录"));  
//			httpPost.setEntity(new UrlEncodedFormEntity(nvps));
			
//			JsonObject obj = new JsonObject(); 
//			obj.addProperty("[username]", "kwashing");
//			obj.addProperty("[password]", "123456");
//			StringEntity se = new StringEntity(obj.toString());   
			
			StringEntity se = new StringEntity("{\"[username]\":\"kwashing\",\"[password]\":\"123456\",\"commit\":\"登录\"}");   
			se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
			httpPost.setEntity(se);
			
			HttpResponse response = client.execute(httpPost);
			HttpEntity entity = response.getEntity();
			
			if (entity != null) {
				InputStream stream = entity.getContent();
				String responseString = convertStreamToString(stream);
				System.out.println(responseString);
//				DataWrapper wrap = new DataWrapper();
//				wrap = wrap.fromJson(responseString);
			}
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	
	private static String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
	
	//获取UUID
	private void gitUuid(){
		
		tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
	    tmDevice = "" + tm.getDeviceId();
	    tmSerial = "" + tm.getSimSerialNumber();
	    androidId = "" + android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
	    UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());
	    uniqueId = deviceUuid.toString();
		Log.e("GetUuid","----------uniqueId = " + uniqueId);
		
	}

	private void init() {
		btnBack = (Button) findViewById(R.login_and_register.btn_back);
		tvTittle = (TextView) findViewById(R.login_and_register.txt_tittle);
		btnLeft = (Button) findViewById(R.login_and_register.btn_left);
		btnRight = (Button) findViewById(R.login_and_register.btn_right);
		llytLogin = (LinearLayout) findViewById(R.login_and_register.llyt_login);
		llytRegister = (LinearLayout) findViewById(R.login_and_register.llyt_register);
		
		//Login
		etLogin_phonenum = (EditText)findViewById(R.id.et_login_phonenum);
		etLogin_pwd = (EditText)findViewById(R.id.et_login_pwd);
		tvForget_pwd = (TextView)findViewById(R.id.tv_forget_pwd);
		btnLogin =  (Button) findViewById(R.id.btn_login);
		//Register
		etPhonenum = (EditText)findViewById(R.id.et_phonenum);
		etPwd = (EditText)findViewById(R.id.et_pwd);
		etConfirm_pwd = (EditText)findViewById(R.id.et_confirm_pwd);
		etName = (EditText)findViewById(R.id.et_name);
		tvRead_treaty = (TextView)findViewById(R.id.tv_read_treaty);
		btnRegister =  (Button) findViewById(R.id.btn_register);
		
		
		btnLogin.setOnClickListener(loginOnClickListener);
		btnRegister.setOnClickListener(registerOnClickListener);

		btnBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				LoginAndRegisterActivity.this.finish();
			}
		});

		btnLeft.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				btnLeft.setBackgroundResource(R.drawable.login_button_active);
				btnRight.setBackgroundResource(R.drawable.regist_button);
				llytLogin.setVisibility(View.VISIBLE);
				llytRegister.setVisibility(View.GONE);
			}
		});

		btnRight.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				btnLeft.setBackgroundResource(R.drawable.login_button);
				btnRight.setBackgroundResource(R.drawable.regist_button_hover);
				llytLogin.setVisibility(View.GONE);
				llytRegister.setVisibility(View.VISIBLE);
			}
		});
	}
	
	private void getValue() {
		login_phonenum = etLogin_phonenum.getText().toString().trim();
		login_pwd = etLogin_pwd.getText().toString().trim();
		
		phonenum = etPhonenum.getText().toString().trim();
		pwd = etPwd.getText().toString().trim();
		confirm_pwd = etConfirm_pwd.getText().toString().trim();
		bitchName= etLogin_phonenum.getText().toString().trim();;
		
		Log.e(TAG, "login_phonenum--------->" + login_phonenum);
	

	}
	
	public static boolean isMobileNO(String mobiles){  
		  
		Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");  
		Matcher m = p.matcher(mobiles);  
		return m.matches();
		  
	}  
	
	
	private OnClickListener loginOnClickListener = new OnClickListener() {
		public void onClick(View v) {
			// TODO Auto-generated method stub
			getValue();
			
			if (!login_phonenum.equals("")) {
				if (isMobileNO(login_phonenum)) {
					if(!login_pwd.equals("")){
						//验证并登陆
						Toast.makeText(getApplicationContext(), "请等待...",
								Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(getApplicationContext(), "请输入密码",
								Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(getApplicationContext(), "请正确填写要注册的手机号码",
							Toast.LENGTH_SHORT).show();
				}
			} else {
				Toast.makeText(getApplicationContext(), "请输入手机号码",
						Toast.LENGTH_SHORT).show();
			}
		}
	};
	
	private OnClickListener registerOnClickListener = new OnClickListener() {
		public void onClick(View v) {
			// TODO Auto-generated method stub
			getValue();
			if (!phonenum.equals("")) {
				if (isMobileNO(phonenum)) {
					if(!pwd.equals("")){
						if(!confirm_pwd.equals("")){
							if(pwd.equals(confirm_pwd)){
								if(!bitchName.trim().equals("")){
									//验证并登陆
									Toast.makeText(getApplicationContext(), "请等待...",
											Toast.LENGTH_SHORT).show();
									//register();
								} else {
									Toast.makeText(getApplicationContext(), "请输入您的尊称",
											Toast.LENGTH_SHORT).show();
								}
							} else {
								Toast.makeText(getApplicationContext(), "密码不一致",
										Toast.LENGTH_SHORT).show();
							}
						}else {
							Toast.makeText(getApplicationContext(), "请输入确认密码",
									Toast.LENGTH_SHORT).show();
						}
					} else {
						Toast.makeText(getApplicationContext(), "请输入密码",
								Toast.LENGTH_SHORT).show();
					}
				}else {
					Toast.makeText(getApplicationContext(), "请正确填写要注册的手机号码",
							Toast.LENGTH_SHORT).show();
				}
			} else {
				Toast.makeText(getApplicationContext(), "请输入手机号码",
						Toast.LENGTH_SHORT).show();
			}
		}
	};

}
